package com.ucode.dcse.handler.crm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ucode.dcse.TableCanalData;
import com.ucode.dcse.handler.TableDataHandler;
import com.ucode.search.crm.model.ESContacts;
import com.ucode.springboot.starter.ESsearch.repository.ElasticsearchDocSourceTemplate;
import com.ucode.tool.util.ListPageModel;
import cn.hutool.core.collection.CollUtil;

@Component("ucode_crm.crm_contacts")
public class ContactsDataHandler implements TableDataHandler {
    
    /**
     * 如果映射Map为空,或者表字段找不到映射，则以数据库为准
     */
    @SuppressWarnings("serial")
    private Map<String, String> table_mapping = new HashMap<String, String>(){{
        put("id", "id");
    }};
    
    @Autowired
    private ObjectMapper mapper; 
    
    @Autowired
    private ElasticsearchDocSourceTemplate<ESContacts, Long> esDocSourceTemplate;

    @Override
    public void handle(TableCanalData tableCanalData) {
        try {
            if(CanalEntry.EventType.INSERT.equals(tableCanalData.getEventType()) ||
                    CanalEntry.EventType.UPDATE.equals(tableCanalData.getEventType()) ){
                
                JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, ESContacts.class); 
                List<ESContacts> list =  (List<ESContacts>)mapper.readValue(tableCanalData.getAfterDatas().toJSONString(), javaType);
                
                if(CollUtil.isNotEmpty(list)){
                    //这里分页批量保存到ES,这里可以根据实际环境来决定一次批量写入多少个，可以通过单线程压测得到最多一次性写多少条数性能最佳，总的来说一次最好不要超过10mb
                    ListPageModel listPageModel = new ListPageModel(list, 200);
                    for (int page = 1; page <= listPageModel.getTotalPages(); page++) {
                        List<ESContacts> pagDatas = listPageModel.getObjects(page);
                        esDocSourceTemplate.save(pagDatas);
                    }
                }
            }else if(CanalEntry.EventType.DELETE.equals(tableCanalData.getEventType())){
                JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, Long.class); 
                List<Long> ids =  (List<Long>)mapper.readValue(tableCanalData.getAfterDatas().toJSONString(), javaType);
                esDocSourceTemplate.deleteByIds(ids, ESContacts.class);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Map<String, String> getMapping() {
        return table_mapping;
    }

}
